package models

import (
	"github.com/beego/beego/v2/client/orm"
	"time"
)

type Followup struct {
	Id         int64
	Archives   *Archives   `orm:"rel(fk);null;on_delete(do_nothing)"`
	Department *Department `orm:"rel(fk);null;on_delete(do_nothing)"`
	CreatedAt  int64
	CreatedBy  string
	Message    string
}

//查询
type FollowupQueryParam struct {
	BaseQueryParam
	Archives int64
}

func (a *Followup) TableName() string {
	return FollowupTableName()
}

func FollowupTableName() string {
	return TableName("ar_followup")
}

//查询分页数据
func FollowupPageList(params *FollowupQueryParam) ([]*Followup, int64) {
	query := orm.NewOrm().QueryTable(FollowupTableName())
	data := make([]*Followup, 0)
	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}
	//cond := orm.NewCondition()
	if params.Archives > 0 {
		query = query.Filter("archives_id", params.Archives)
	}
	query = query.Filter("department_id", CurLoginUserInfo.DepartmentId)

	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&data)

	return data, total
}

/**
* 添加随访
 */
func FollowupAdd(a *Followup) (int64, error) {
	dep := Department{}
	dep.Id = CurLoginUserInfo.DepartmentId
	a.Department = &dep
	a.CreatedAt = time.Now().Unix()
	a.CreatedBy = CurLoginUserInfo.RealName
	return orm.NewOrm().Insert(a)
}

//删除随访
func FollowupDeleteById(id int64) error {
	o := orm.NewOrm().QueryTable(FollowupTableName())
	if _, err := o.Filter("id", id).Delete(); err != nil {
		return err
	}
	return nil
}